<script setup name="User" lang="ts">
import type { PaginationProps } from 'ant-design-vue'
import { UserOutlined } from '@ant-design/icons-vue'
import api from '@/api/system/user'
import type { UserForm, UserQuery, UserVO } from '@/api/system/user/types'
import { treeselect } from '@/api/system/dept'
import type { DeptVO } from '@/api/system/dept/types'
import type { RoleVO } from '@/api/system/role/types'
import type { PostVO } from '@/api/system/post/types'
import AuthRole from '~/pages/system/user/authRole.vue'

const { proxy } = getCurrentInstance() as ComponentInternalInstance

const { sys_normal_disable, sys_user_sex } = toRefs<any>(proxy?.useDict('sys_normal_disable', 'sys_user_sex', 'id_type'))
const message = useMessage()
const modal = useModal()
const userList = ref<UserVO[]>()
const loading = ref(true)
const openAuthModal = ref(false)
const openAuthUserId = ref()
const authRuleRef = ref()
const ids = ref<Array<number | string>>([])
const deptName = ref('')
const deptOptions = ref<DeptVO[]>([])
const initPassword = ref<string>('')
const postOptions = ref<PostVO[]>([])
const roleOptions = ref<RoleVO[]>([])

const deptTreeRef = ref()
const userFormRef = ref()
const formDialogRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

const columns = shallowRef([

  {
    title: '姓名',
    dataIndex: 'nickName',
    ellipsis: true,
  },
  {
    title: '系统登录名',
    dataIndex: 'userName',
    ellipsis: true,
  },

  {
    title: '手机号码',
    dataIndex: 'phonenumber',
    ellipsis: true,
  },
  {
    title: '部门',
    dataIndex: 'deptName',
    ellipsis: true,
  },

  {
    title: '授权项目数',
    dataIndex: 'projectNumber',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'userId',
    width: '280px',
    ellipsis: true,
  },
])

const initFormData: UserForm = {
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: undefined,
  password: '',
  phonenumber: undefined,
  email: undefined,
  sex: undefined,
  status: '0',
  remark: '',
  type: 1,
  postIds: [],
  roleIds: [],
}
const data = reactive<PageData<UserForm, UserQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: '',
    phonenumber: '',
    status: undefined,
    type: null,
    deptId: undefined,
  },
  rules: {
    userName: [{ required: true, message: '登录账号不能为空', trigger: 'blur' }, { min: 2, max: 20, message: '登录账号长度必须介于 2 和 20 之间', trigger: 'blur' }],
    nickName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    postIds: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
    sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }, { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }],
    email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }],
    phonenumber: [{ required: true, message: '手机号码不能为空', trigger: 'blur' }, { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs<PageData<UserForm, UserQuery>>(data)

const pagination: PaginationProps = reactive({
  pageSize: 10,
  current: 1,
  total: 0,
  showSizeChanger: false,
  showQuickJumper: false,
  showTotal: (total: number) => `总计：${total}条数据`,
  onChange(current: number, pageSize: number) {
    pagination.current = current
    pagination.pageSize = pageSize
    queryParams.value.pageNum = current
    queryParams.value.pageSize = pageSize
    getList()
  },
})

/** 根据名称筛选部门树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value)
  },
  {
    flush: 'post', // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  },
)

/** 查询部门下拉树结构 */
async function getTreeSelect() {
  const res = await api.deptTreeSelect()
  deptOptions.value = res.data
}

/** 查询用户列表 */
async function getList() {
  loading.value = true
  const res = await api.listUser(queryParams.value)
  console.log(res)
  loading.value = false
  userList.value = res.rows
  pagination.total = res.total
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  pagination.current = 1
  getList()
}

/** 搜索按钮操作 */
function queryTextSearch(value) {
  queryParams.value.userName = value
  queryParams.value.pageNum = 1
  pagination.current = 1
  getList()
}

/** 用户状态修改  */
async function handleStatusChange(row: UserVO) {
  const text = row.status === '0' ? '启用' : '停用'
  modal.confirm({
    title: `确认要"${text}""${row.userName}"用户吗?`,
    onOk: async () => {
      await api.changeUserStatus(row.userId, row.status)
      message.success(`${text}成功`)
    },
    onCancel: async () => {
      row.status = row.status === '0' ? '1' : '0'
    },
  })
}

/** 用户状态修改  */
async function handleDelete(row: UserVO) {
  const userIds = row?.userId || ids.value
  modal.confirm({
    title: `确认要删除"${row.userName}"用户吗?`,
    onOk: async () => {
      await api.delUser(userIds)
      message.success(`删除成功`)
    },
    onCancel: async () => {
      row.status = row.status === '0' ? '1' : '0'
    },
  })
}

/** 初始化部门数据 */
async function initTreeData() {
  // 判断部门的数据是否存在，存在不获取，不存在则获取
  if (deptOptions.value === undefined) {
    const { data } = await treeselect()
    deptOptions.value = data
  }
}

/** 重置操作表单 */
function reset() {
  form.value = { ...initFormData }
  userFormRef.value?.resetFields()
}

/** 取消按钮 */
function cancel() {
  dialog.visible = false
  reset()
}

/** 新增按钮操作 */
async function handleAdd() {
  reset()
  const { data } = await api.getUser()
  dialog.visible = true
  dialog.title = '新增职员'
  await initTreeData()
  postOptions.value = data.posts
  roleOptions.value = data.roles
  form.value.password = initPassword.value.toString()
}

/** 修改按钮操作 */
async function handleUpdate(row?: UserForm) {
  reset()
  const userId = row?.userId || ids.value[0]
  const { data } = await api.getUser(userId)
  dialog.visible = true
  dialog.title = '编辑职员'
  await initTreeData()
  Object.assign(form.value, data.user)
  postOptions.value = data.posts
  roleOptions.value = data.roles
  form.value.postIds = data.postIds
  form.value.roleIds = data.roleIds
  form.value.password = ''
}

/** 提交按钮 */
function submitForm(type: number | string) {
  userFormRef.value?.validate().then(async () => {
    if (form.value.userId) {
      form.value.avatar = null
      await api.updateUser(form.value)
      message.success('修改成功')
    }
    else {
      const res = await api.addUser(form.value)
      message.success('保存成功')
      if (type === 1)
        startAuthRole(res.data)
    }

    dialog.visible = false
    await getList()
  })
}

/**
 * 关闭用户弹窗
 */
function closeDialog() {
  dialog.visible = false
  resetForm()
}

/**
 * 重置表单
 */
function resetForm() {
  userFormRef.value?.resetFields()
  userFormRef.value?.clearValidate()

  form.value.id = undefined
  form.value.status = '1'
}
function startAuthRole(userId: number | string) {
  openAuthUserId.value = userId
  openAuthModal.value = true
}
/** 提交按钮（数据权限） */
async function submitAuthModal() {
  await authRuleRef.value.submitForm()
}

function saveAuthRoleSuccess() {
  openAuthModal.value = false
  message.success('授权成功')
  getList()
}

// 已取消和已结算的
function rowClassName(record: UserVO) {
  if (record.status === '1')
    return 'depart-row-class'
}

onMounted(() => {
  getTreeSelect() // 初始化部门数据
  getList() // 初始化列表数据
  proxy?.getConfigKey('sys.user.initPassword').then((response) => {
    initPassword.value = response.data
  })
})
</script>

<template>
  <div>
    <div class="p-2">
      <bh-table :row-class-name="rowClassName" :loading="loading" :columns="columns" :show-filtering="false" placeholder="输入姓名、手机号，按回车键搜索" :data-source="userList" :pagination="pagination" @on-query="queryTextSearch" @show-modal="handleAdd">
        <template #filter>
          <a-tree-select
            v-model:value="queryParams.deptId"
            style="width: 100%"
            :dropdown-match-select-width="false"
            :tree-data="deptOptions"
            :field-names="{ value: 'id', label: 'label', children: 'children' }"
            value-key="id"
            placeholder="全部部门"
            @change="handleQuery"
          />
          <a-select v-model:value="queryParams.status" placeholder="全部状态" allow-clear style="width: 100px" @change="handleQuery">
            <a-select-option
              v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
              :value="dict.value"
            >
              {{ dict.label }}
            </a-select-option>
          </a-select>
        </template>
        <template #tableBody="{ column, record }">
          <template v-if="column.dataIndex === 'nickName'">
            <a-space>
              <a-avatar v-if="record.avatar" :size="35" :src="record.avatar">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <a-avatar v-else :size="35">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <span>{{ record.nickName }}</span>
            </a-space>
          </template>
          <template v-if="column.dataIndex === 'userId'">
            <a-space v-if="record.userId !== 1" :size="0">
              <a-button type="link" @click="startAuthRole(record.userId)">
                <span>授权</span>
              </a-button>
              <a-button type="link" @click="handleUpdate(record)">
                <span>编辑</span>
              </a-button>

              <a-button v-hasPermi="['system:user:remove']" type="link" @click="handleDelete(record)">
                删除
              </a-button>

              <span class="op-span">
                <a-switch v-model:checked="record.status" checked-value="0" un-checked-value="1" @change="handleStatusChange(record)" />
              </span>
            </a-space>
            <span v-else />
          </template>
        </template>
      </bh-table>

      <!-- 添加或修改用户配置对话框 -->
      <a-modal
        ref="formDialogRef" v-model:open="dialog.visible"
        :mask-closable="false" :keyboard="false" :title="dialog.title" width="700px" append-to-body
        destroy-on-close @close="closeDialog"
      >
        <a-form ref="userFormRef" :hide-required-mark="true" class="block-form" :model="form" :rules="rules" layout="vertical">
          <div class="pl-8px pr-8px">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="姓名" name="nickName" class="required">
                  <a-input v-model:value="form.nickName" placeholder="请输入姓名" max-length="30" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="性别" class="required" name="sex">
                  <a-select v-model:value="form.sex" style="width: 100%" placeholder="请选择">
                    <a-select-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value">
                      {{ dict.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item v-if="form.userId === undefined" label="登录账号" class="required" name="userName">
                  <a-input v-model:value="form.userName" placeholder="请输入登录账号" max-length="30" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item v-if="form.userId === undefined" class="required" label="用户密码" name="password">
                  <a-input-password
                    v-model:value="form.password" placeholder="请输入用户密码" type="password" max-length="20"
                    show-password
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号码" name="phonenumber" class="required">
                  <a-input v-model:value="form.phonenumber" placeholder="请输入手机号码" max-length="11" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="归属部门" class="required" name="deptId">
                  <a-tree-select
                    v-model:value="form.deptId"
                    style="width: 100%"
                    :tree-data="deptOptions"
                    :field-names="{ value: 'id', label: 'label', children: 'children' }"
                    value-key="id"
                    placeholder="请选择归属部门"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="岗位" class="required" name="postIds">
                  <a-select v-model:value="form.postIds" mode="multiple" style="width: 100%" placeholder="请选择">
                    <a-select-option
                      v-for="item in postOptions"
                      :key="item.postId"
                      :label="item.postName"
                      :value="item.postId"
                      :disabled="item.status === '1'"
                    >
                      {{ item.postName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="24">
                <a-form-item label="备注">
                  <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </a-form>
        <template #footer>
          <div class="dialog-footer">
            <a-button @click="cancel()">
              取 消
            </a-button>

            <a-button v-if="form.userId === undefined" @click="submitForm(1)">
              保存并授权
            </a-button>

            <a-button type="primary" @click="submitForm(0)">
              保 存
            </a-button>
          </div>
        </template>
      </a-modal>

      <!-- 分配角色数据权限对话框 -->
      <a-modal v-model:open="openAuthModal" :mask-closable="false" :keyboard="false" destroy-on-close title="授权" width="800px">
        <AuthRole ref="authRuleRef" :user-id="openAuthUserId" @success="saveAuthRoleSuccess" />
        <template #footer>
          <div class="dialog-footer">
            <a-button @click="openAuthModal = false">
              取 消
            </a-button>

            <a-button type="primary" @click="submitAuthModal">
              保 存
            </a-button>
          </div>
        </template>
      </a-modal>
    </div>
  </div>
</template>

<style lang="less" scoped>
.op-span{
  cursor: pointer;
  *{
    font-size: 12px;
    color: var(--bh-color-9);
  }
  span{
    padding-left: 5px;
  }

}
:deep(.op-span){
  .ant-switch-checked{
    background: #00DBB3
  }
}
</style>
